// 定义了一个默认的state
const defaultState = {
  count: 0
}

// 更改数据state的函数, 返回一个新的状态
// reduce函数，归并函数，纯函数
const reducer = (state, action) => {
  switch(action.type) {
    case 'add':
      return {
        count: state.count + 1
      }
    case 'minus':
      return {
        count: state.count - 1
      }
    default:
      return state
  }
}

// store
const createStore = (reducer, defaultState) => {
  // 状态 state
  let state = defaultState
  
  // subscribers: 订阅者们
  const subscribers = []

  // dispatch函数，接受action, 返回一个新的状态
  const dispatch = (action) => {
    // 更新state, 通过reducer返回的新状态
    state = reducer(state, action)

    // 通知所有的订阅者，状态更新了
    subscribers.forEach(f => f())
  }

  // 返回最新的状态
  const getState = () => {
    return state
  }

  // 响应数据更新的函数
  const subscribe = (f) => {
    subscribers.push(f)
  }

  return {
    dispatch,
    getState,
    subscribe
  }
}

// 调用createStore
const store = createStore(reducer, defaultState)

store.subscribe(() => {
  console.log(store.getState())
})

// store.dispatch({
//   type: 'add'
// })

setInterval(() => {
  store.dispatch({
    type: 'add'
  })
}, 2000)